<?php
/**
 * Created by PhpStorm.
 * User: 咔咔
 * Date: 2020/9/21
 * Time: 19:04
 */

namespace container;


class Container
{
    /**
     * 存放容器
     * @var array
     */
    public $instances = [];

    /**
     * 容器的对象实例
     * @var array
     */
    protected static $instance;

    /**
     * 定义一个私有的构造函数防止外部类实例化
     * Container constructor.
     */
    private function __construct() {

    }

    /**
     * 获取当前容器的实例(单例模式)
     * @return array|Container
     */
    public static function getInstance ()
    {
        if(is_null(self::$instance)){
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function set ($key,$value)
    {
        return $this->instances[$key] = $value;
    }

    /**
     * User : 咔咔
     * Notes: 获取容器里边的实例  使用反射
     * Time :2020/9/21 22:04
     * @param $key
     * @return mixed
     */
    public function get ($key)
    {
        if(!empty($this->instances[$key])){
            $key = $this->instances[$key];
        }

        $reflect = new \ReflectionClass($key);
        // 获取类的构造函数
        $c = $reflect->getConstructor();

        if(!$c){
            return new $key;
        }

        // 获取构造函数的参数
        $params = $c->getParameters();
        foreach ($params as $param) {
            /**
            ReflectionClass Object
            (
                [name] => container\dependency\Car
            )
             */
            $class = $param->getClass();

            if(!$class){

            }else{
                // 返回是对象：container\dependency\Car
                $args[] = $this->get($class->name);
            }
        }

        // 从给出的参数创建一个新的类实例
        return $reflect->newInstanceArgs($args);
    }
}